/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controle.mensagem;

import controle.usuario.Sessao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import persistencia.dao.AbstractDAO;
import persistencia.objetos.Mensagens;
import persistencia.objetos.Usuarios;
import utils.*;

/**
 *
 * @author Milton
 */
public class ServletActionMensagen extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        ServletContext context;
        RequestDispatcher despachante;
        String destinatario;
        String titulo;
        String descricao;
        String url;
        
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            
            //Verificar se user esta autenticado
            if(Sessao.sessaoAtiva(request.getSession(false))){
                
                int act = action==null ? 10 : Integer.parseInt(action);

                switch (act) {
                        //Cadastrar
                    case 1:
                        
                        destinatario = request.getParameter("destinatario");
                        titulo = request.getParameter("titulo");
                        descricao = request.getParameter("descricao");

                        if(!destinatario.equals("")&& !titulo.equals("")&& !descricao.equals("")){

                            Usuarios userSessao = new Usuarios();
                            userSessao.setIdUsuario(Sessao.getUserRegistrado(request.getSession(false)).getIdUsuario());
                            Usuarios dest = new Usuarios();
                            dest.setIdUsuario(Integer.parseInt(destinatario));

                            java.sql.Date da = Date.getDataHoje();
                            java.sql.Time ho = Horas.getHoraAgora();

                            Mensagens mens = new Mensagens(userSessao,dest , titulo, descricao, da, ho);

                            AbstractDAO dao = new AbstractDAO();
                            if(dao.cadastrar(mens)){

                                request.setAttribute("mensagem",Mensagen.Alert("Mensagen enviada com sucesso !"));
                                //passar um path pra entrar no defalt
                                url =  "/ServletActionMensagen?action=9";

                                context = getServletContext();
                                despachante = context.getRequestDispatcher(url);
                                despachante.forward(request, response);
                            }else{

                                request.setAttribute("mensagem",Mensagen.Alert("Falha ao enviar mensagen !\n Tente novamente."));

                                url =  "/ServletActionMensagen?action=9";

                                context = getServletContext();
                                despachante = context.getRequestDispatcher(url);
                                despachante.forward(request, response);              
                            }
                        }else{
                            request.setAttribute("btnAcao","Enviar");
                            request.setAttribute("mensagem",Mensagen.Alert("Preencha os Campos Obrigatórios."));

                            url =  "/ServletActionMensagen?action=9";

                            context = getServletContext();
                            despachante = context.getRequestDispatcher(url);
                            despachante.forward(request, response);
                        }
                    break;
                        //Editar - responder
                    case 2:
                        
                        Usuarios use = Sessao.getUserRegistrado(request.getSession());

                        String idDest = request.getParameter("id");
                        String para = request.getParameter("para");

                        request.setAttribute("idDestinatario",idDest);
                        request.setAttribute("nome",para);

                        url =  "/Interface/ResponderMensagen.jsp";

                        context = getServletContext();
                        despachante = context.getRequestDispatcher(url);
                        despachante.forward(request, response);                      
                    break;
                        //Excluir
                    case 3:

                        String id = request.getParameter("id");              
                        out.println(Integer.parseInt(id));
                        AbstractDAO del = new AbstractDAO();
                        
                        if(del.excluir("Mensagens", "idMensagem", Integer.parseInt(id))){
                           // out.print("Exclui");
                            request.setAttribute("alertas",Mensagen.Alert("Mensagen excluida com sucesso !"));
                        }else{
                           // out.print("Não exclui");
                            request.setAttribute("alertas",Mensagen.Alert("Falha ao excluir mensagen!"));
                        }    
                    //break;
                       //Listar 
                    case 4:
                       
                        List<Mensagens> msnEnv=null;
                        List<Mensagens> msnRec=null;
                        Mensagens mensage;
                        Usuarios user = Sessao.getUserRegistrado(request.getSession(false));
                        String str="<table border='1'>"
                        + "<tr><th>Titulo</th><th>Mensagen</th><th>Data</th><th>Para</th><th colspan='2'>Ações</th></tr>";
                        
                        msnEnv = new AbstractDAO().consultar("Mensagens", "idUsuarioRemetente="+user.getIdUsuario());

                        for(int i=0;i<msnEnv.size();i++){
                            mensage = (Mensagens) msnEnv.get(i);
                            
                            str +="<tr><td>"+ mensage.getTitulo()+"</td><td>" + mensage.getDescricao()+"</td>"
                            + "<td>"+mensage.getDataCriacao()+"</td>" + "<td>"+mensage.getUsuariosByIdUsuarioDestinatario().getNome()+"</td>"
                                   // + "<td><a href=ServletActionMensagen?action=2&id="+mensage.getUsuariosByIdUsuarioDestinatario().getIdUsuario()+"&para="+mensage.getUsuariosByIdUsuarioDestinatario().getNome()+" > Responder </a></td>"
                                    + "<td><a href=ServletActionMensagen?action=3&id="+mensage.getIdMensagem()+"> Deletar </a></td></tr>";               
                        }
                        
                        str+="</table>";
                        
                        msnRec = new AbstractDAO().consultar("Mensagens", "idUsuarioDestinatario="+user.getIdUsuario()); 
                        String st="<table border='1'>"
                        + "<tr><th>Titulo</th><th>Mensagen</th><th>Data</th><th>De</th><th colspan='2'>Ações</th></tr>";
                        
                        msnEnv = new AbstractDAO().consultar("Mensagens", "idUsuarioRemetente="+user.getIdUsuario());

                        for(int i=0;i<msnRec.size();i++){
                            mensage = (Mensagens) msnRec.get(i);
                            st +="<tr><td>"+ mensage.getTitulo()+"</td><td>" + mensage.getDescricao()+"</td>"
                            + "<td>"+mensage.getDataCriacao()+"</td>"+"<td>"+mensage.getUsuariosByIdUsuarioRemetente().getNome()+"</td>"
                                     + "<td><a href=ServletActionMensagen?action=2&id="+mensage.getUsuariosByIdUsuarioRemetente().getIdUsuario()+"&para="+mensage.getUsuariosByIdUsuarioRemetente().getNome()+" > Responder </a></td>"
                                    + "<td><a href=ServletActionMensagen?action=3&id="+mensage.getIdMensagem()+"> Deletar </a></td></tr>";               
                        }
                        
                        st+="</table>";
                        
                        if(msnEnv.isEmpty()){
                            request.setAttribute("alertas",Mensagen.Alert("Você não enviou mensagens!"));              
                        }else{
                            request.setAttribute("msnEnv",str);
                        }   
                        if(msnRec.isEmpty()){
                            request.setAttribute("alertas",Mensagen.Alert("Não há mensagens novas !"));              
                        }else{
                            request.setAttribute("msnRec",st);
                        }   
                         url=  "/Interface/ListarMensagens.jsp";

                        context = getServletContext();
                        despachante = context.getRequestDispatcher(url);
                        despachante.forward(request, response);                    

                    break;
                    default:
                        
                        //Consultar usuarios
                        List<Usuarios> usuarios;
                        Usuarios uses = (Usuarios) Sessao.getUserRegistrado(request.getSession(false));

                       usuarios = new AbstractDAO().consultar("Usuarios", "idUsuario!="+uses.getIdUsuario());
                       
                        request.setAttribute("valueAction","1");
                        request.setAttribute("btnAcao","Enviar");
                        
                        request.setAttribute("user", usuarios);
                        
                        String u =  "/Interface/CadastrarMensagen.jsp";
                        
                        context = getServletContext();
                        despachante = context.getRequestDispatcher(u);
                        despachante.forward(request, response);
                }             
            }else{
                
                request.setAttribute("mensagem",Mensagen.Alert("Usuario não autenticado!"));
                
                url =  "/";

                context = getServletContext();
                despachante = context.getRequestDispatcher(url);
                despachante.forward(request, response);
            }
       
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
